/**
 * 单个扫描结果弹窗
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Tag, Button, Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import ListLoading from 'atComponents/ListLoading';
import File from 'components/buildResultIssues/securityFile';
import UsersAvatar from '@alife/teamix-at-users-avatar';
import utils from 'utils';
import IgnoreModal from 'components/ignoreIssueModal';
import { ENUM } from 'utils/constants';
import './index.scss';
import intl from '../../locale';

const prefix = 'single-build-detail';

const stateMap = ENUM.issueStausMap;
const { organization } = window.FORCE;

export default class buildDetailDialog extends React.Component {
  static propTypes = {
    // build数据
    build: PropTypes.object,
    // 当前issue
    issue: PropTypes.object,
    onClose: PropTypes.func,
    projectId: PropTypes.number,
    updateCommitId: PropTypes.func,
  };

  static defaultProps = {
    build: {},
    issue: {},
    onClose: () => {},
    projectId: window.FORCE.pathResource ? window.FORCE.pathResource.id : null,
    closeCommitDetail: () => {},
    updateCommitId: () => {},
  };

  constructor(props) {
    super(props);
    this.dialog = React.createRef();
    this.state = {
      activityList: [],
      isLoadingActivity: true,
      isIgnoreModalShow: false,
      issue: props.issue,
      isNeedRefreshTable: false,
      issue_list: [],
    };
  }

  componentDidMount() {
    this.getIssuesDetail();
    this.getActivity();
  }

  // 改变状态，更新数据
  updateInfo = (issue) => {
    this.setState({
      issue,
      // 更新了状态，需要关闭时更新所有表格数据
      isNeedRefreshTable: true,
    });

    this.getActivity();
  };

  onClose = () => {
    const { onClose, refreshData } = this.props;
    const { isNeedRefreshTable } = this.state;
    onClose && onClose();
    isNeedRefreshTable && refreshData && refreshData();
  };

  // 获取操作记录
  getActivity = () => {
    const { build } = this.props;
    const { issue } = this.state;
    exceed
      .fetch({
        api: 'projects.builds.single.activity',
        params: {
          org_id: organization.id,
        },

        data: {
          build_id: build.id,
          issue_id: issue.build_issue_id,
        },
      })
      .then((result) => {
        const list = result.slice(1);
        this.setState({
          isLoadingActivity: false,
          activityList: list,
        });
      })
      .fail((err) => {
        console.error(err);
        this.setState({
          isLoadingActivity: false,
        });
      });
  };

  // 供子元素异步加载后强制更新dialog，否则会导致不出滚动条
  forceUpdateDialog = () => {
    // this.dialog.current.forceUpdate();
  };

  renderCommitId = (commitId) => {
    if (!commitId) {
      return null;
    }
    return (
      <Button
        type="primary"
        text
        style={{ margin: '0 4px', flexShrink: 0 }}
        onClick={(e) => {
          this.props.onClose();
          this.props.updateCommitId(e, commitId);
        }}
      >
        {commitId.slice(0, 8)}
      </Button>
    );
  };

  renderActivityItem = (item) => {
    const operationType = item.operation_type ? item.operation_type.toLowerCase() : '';
    const { commit_id, reason } = item.extra_info ? item.extra_info : {};
    let text = '';
    switch (operationType) {
      case 'created':
        text = intl.get({
          id: 'code-assets.components.issueDetailDialog.ScanToFindProblems',
          defaultMessage: '扫描发现问题',
        });
        break;
      case 'resolved':
      case 'fixed':
        text = (
          <span className="detail">
            <span>{item.operator_name}</span>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.Submitted',
              defaultMessage: '提交',
            })}
            {this.renderCommitId(commit_id)}
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.FixedTheIssue',
              defaultMessage: '修复了问题',
            })}
          </span>
        );

        break;
      case 'unresolved':
      case 'new':
        text = (
          <span className="detail">
            <span>{item.operator_name}</span>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.Submitted',
              defaultMessage: '提交',
            })}
            {this.renderCommitId(commit_id)}
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.TheCurrentIssueIsNot',
              defaultMessage: '未解决当前问题',
            })}
          </span>
        );

        break;
      case 'ignore':
      case 'ignored': {
        text = (
          <span className="detail">
            <span>{item.operator_name}</span>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.IgnoredProblem',
              defaultMessage: '忽略了问题',
            })}
            {reason
              ? intl.get(
                  {
                    id: 'code-assets.components.issueDetailDialog.ReasonForClosingReason',
                    defaultMessage: '，关闭原因：{reason}',
                  },
                  { reason },
                )
              : ''}
          </span>
        );
        break;
      }
      case 'open':
      case 'reopened':
        text = (
          <span className="detail">
            <span>{item.operator_name}</span>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.TheProblemIsReopenedAnd',
              defaultMessage: '重新打开了问题，扫描结果问题未解决',
            })}
          </span>
        );

        break;
      case 'close':
        text = (
          <span className="detail">
            <span>{item.operator_name}</span>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.TheProblemWasManuallyClosed',
              defaultMessage: '手动关闭了问题，关闭原因：',
            })}
            {reason}
          </span>
        );

        break;
      default:
        text = '';
    }

    return (
      <div className={`${prefix}-history-list-item`}>
        <div className={`${prefix}-history-list-item-left`}>{text}</div>
        <div className={`${prefix}-history-list-item-right`}>
          {utils.getBeautyTime(item.gmt_create)}
        </div>
      </div>
    );
  };

  closeIgnoreModal = () => {
    this.setState({
      isIgnoreModalShow: false,
    });
  };

  renderFooter = (status) => {
    const { isLoadingActivity } = this.state;
    if (isLoadingActivity) {
      return null;
    }
    const { btnStatus } = stateMap[status];

    if (btnStatus === 1) {
      return (
        <div className={`${prefix}-footer`}>
          <Button
            type="primary"
            onClick={() => {
              this.setState({
                isIgnoreModalShow: true,
              });
            }}
          >
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.Ignore',
              defaultMessage: '忽略问题',
            })}
          </Button>
        </div>
      );
    } else if (btnStatus === 2) {
      return (
        <div className={`${prefix}-footer`}>
          <Button type="primary" onClick={this.reopenIssue}>
            {intl.get({
              id: 'code-assets.components.issueDetailDialog.Reopen',
              defaultMessage: '重新打开',
            })}
          </Button>
        </div>
      );
    } else {
      return null;
    }
  };

  reopenIssue = () => {
    const { isReopening } = this.state;
    if (isReopening) {
      return;
    }
    const { projectId } = this.props;
    const { issue } = this.state;
    exceed
      .fetch({
        api: 'project.build.issue.reopen',
        params: { projectId },
        data: { detail: issue },
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.issueDetailDialog.TheProblemHasBeenReopened',
            defaultMessage: '问题重新打开成功',
          }),
        });

        this.updateInfo({
          ...issue,
          status: result.status,
        });

        this.setState({ isReopening: false });
      })
      .fail(() => {
        this.setState({ isReopening: false });
      });
  };

  // 转化成通用格式
  commonFile = () => {
    const { issue } = this.state;
    // 转化成通用格式
    const file = {
      file_name: issue.file_name,
      issue_count_info: { blocker: 0, critical: 0, major: 0, ...{ [issue.level]: 1 } },
      issue_id_list: [issue.build_issue_id],
      build_result_id: issue.build_result_id,
    };
    return file;
  };

  getIssuesDetail(cb) {
    const { projectId } = this.props;
    const file = this.commonFile();

    // 在详情页issue_id_list长度为1,不需要每50个请求一次
    const { issue_id_list } = file;

    const buildId = file.build_result_id;

    exceed
      .fetch({
        api: 'projects.builds.issues.batch',
        params: { projectId: projectId || window.FORCE.pathResource.id, buildId },
        data: {
          issue_ids: issue_id_list.join(','),
        },
      })
      .then((result) => {
        result.shift();

        this.setState({
          issue_list: result,
        });

        cb && cb(result[0]);
      })
      .fail(console.log);
  }

  render() {
    const { build, projectId } = this.props;
    const { isLoadingActivity, activityList, isIgnoreModalShow, issue } = this.state;
    const file = this.commonFile();

    // 当前状态
    const status = issue.status.toLowerCase();
    // 获取引入的记录
    // const createdActivity = activityList.find(
    //   (item) => item.operation_type && item.operation_type.toLowerCase() === 'created',
    // );

    // const createCommitId =
    // (createdActivity && createdActivity.extra_info && createdActivity.extra_info.commit_id) || '';
    const createCommitId = this.state.issue_list[0] ? this.state.issue_list[0].intro_commit : '';

    // 未处理--忽略按钮 已忽略--重新打开
    const footer = this.renderFooter(status);
    return (
      <React.Fragment>
        <Dialog
          title={<div>{issue.title}</div>}
          visible
          style={{ width: 800, minHeight: '224px', overflowY: 'auto' }}
          onCancel={this.onClose}
          onClose={this.onClose}
          footer={footer || false}
          isFullScreen
          id="build-detail-dialog"
          ref={this.dialog}
        >
          <div>
            {isLoadingActivity ? (
              <ListLoading />
            ) : (
              <div className={prefix}>
                <div className={`${prefix}-info`}>
                  <div className={`info-state ${prefix}-info-item`}>
                    <div className={`${prefix}-info-item-left`}>
                      {intl.get({
                        id: 'code-assets.components.issueDetailDialog.ProblemStatus',
                        defaultMessage: '问题状态',
                      })}
                    </div>
                    <div className={`${prefix}-info-item-right`} style={{ marginRight: -4 }}>
                      <Tag color={stateMap[status].color}>{stateMap[status].text}</Tag>
                    </div>
                  </div>
                  <div className={`info-user ${prefix}-info-item`}>
                    <div className={`${prefix}-info-item-left`}>
                      {intl.get({
                        id: 'code-assets.components.issueDetailDialog.Introduced',
                        defaultMessage: '引入人',
                      })}
                    </div>
                    <div className={`${prefix}-info-item-right`} style={{ paddingLeft: 5 }}>
                      <UsersAvatar
                        dataSource={[
                          {
                            id: '',
                            name: issue.owner,
                            avatarUrl: issue.avatar || '',
                          },
                        ]}
                        size="xs"
                        borderColor={'#f7f7f7'}
                      />

                      <span style={{ marginLeft: 8 }}>{issue.owner}</span>
                    </div>
                  </div>
                  {/* <div className={`info-file ${prefix}-info-item`}>
                     <div className={`${prefix}-info-item-left`}>文件</div>
                     <div className={`${prefix}-info-item-right`}>{issue.file_name}</div>
                   </div> */}
                  <div className={`info-version ${prefix}-info-item`}>
                    <div className={`${prefix}-info-item-left`}>
                      {intl.get({
                        id: 'code-assets.components.issueDetailDialog.ImportAndSubmit',
                        defaultMessage: '引入提交',
                      })}
                    </div>
                    <div className={`${prefix}-info-item-right`}>
                      <span style={{ marginRight: 8 }}>{build.branch}</span>
                      {this.renderCommitId(createCommitId)}
                    </div>
                  </div>
                  <div className={`info-desc ${prefix}-info-item`}>
                    <div className={`${prefix}-info-item-left`}>
                      {intl.get({
                        id: 'code-assets.components.issueDetailDialog.ProblemDescription',
                        defaultMessage: '问题描述',
                      })}
                    </div>
                    <div className={`${prefix}-info-item-right`}>
                      <div className="build-issues">
                        <File
                          file={file}
                          showIssuesInFile
                          build={build}
                          commitId={createCommitId}
                          projectId={projectId}
                          isInProjectSecurity
                          forceUpdateDialog={this.forceUpdateDialog}
                        />
                      </div>
                    </div>
                  </div>
                </div>
                <div className={`${prefix}-history`}>
                  <div className={`${prefix}-history-title`}>
                    {intl.get({
                      id: 'code-assets.components.issueDetailDialog.IssueDynamics',
                      defaultMessage: '问题动态',
                    })}
                  </div>
                  <div className={`${prefix}-history-list`}>
                    {activityList.map((item) => {
                      return this.renderActivityItem(item);
                    })}
                  </div>
                </div>
              </div>
            )}
          </div>
        </Dialog>
        {isIgnoreModalShow && (
          <IgnoreModal
            issue={issue}
            isModalOpen={isIgnoreModalShow}
            onClose={this.closeIgnoreModal}
            onSuccess={this.updateInfo}
            projectId={projectId}
          />
        )}
      </React.Fragment>
    );
  }
}
